<template>
  <view class="documents-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <view class="back-section" @click="goBack">
          <text class="back-icon">←</text>
          <text class="header-title">文档管理</text>
        </view>
        <view class="header-actions">
          <button class="upload-btn" @click="showUploadDialog">
            <text class="upload-icon">📤</text>
            <text>上传</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-bar">
        <text class="search-icon">🔍</text>
        <input
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索文档..."
          @confirm="handleSearch"
        />
        <button v-if="searchKeyword" class="clear-btn" @click="clearSearch">
          ✕
        </button>
      </view>
    </view>

    <!-- 文档列表 -->
    <scroll-view
      class="documents-list"
      scroll-y="true"
      @scrolltolower="loadMore"
      refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="documents.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">📁</text>
        <text class="empty-text">暂无文档</text>
        <button class="empty-btn" @click="showUploadDialog">立即上传</button>
      </view>

      <view v-else class="documents-grid">
        <view
          v-for="doc in documents"
          :key="doc.id"
          class="document-card"
          @click="viewDocument(doc)"
        >
          <!-- 文档图标 -->
          <view class="document-icon">
            <text class="icon-text">{{
              getFileIcon(doc.source || doc.title)
            }}</text>
          </view>

          <!-- 文档信息 -->
          <view class="document-info">
            <text class="document-name" :title="doc.title">{{
              truncateText(doc.title, 15)
            }}</text>
            <text class="document-size">{{
              formatFileSize(doc.content ? doc.content.length : 0)
            }}</text>
            <text class="document-date">{{
              formatRelativeTime(doc.createdAt)
            }}</text>
          </view>

          <!-- 操作菜单 -->
          <view class="document-actions" @click.stop>
            <button class="action-btn" @click="showActions(doc)">
              <text class="action-icon">⋮</text>
            </button>
          </view>

          <!-- 文档状态 -->
          <view class="document-status" :class="getStatusClass(doc.status)">
            <text class="status-text">{{ getStatusText(doc.status) }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-if="noMore && documents.length > 0" class="no-more">
        <text class="no-more-text">没有更多文档了</text>
      </view>
    </scroll-view>

    <!-- 上传弹窗 -->
    <view v-if="showUpload" class="upload-overlay" @click="hideUploadDialog">
      <view class="upload-dialog" @click.stop>
        <view class="upload-header">
          <text class="upload-title">上传文档</text>
          <button class="close-btn" @click="hideUploadDialog">✕</button>
        </view>
        <view class="upload-content">
          <!-- 使用专门的上传组件 -->
          <DocumentUploadSmart
            button-text="选择文件"
            upload-text="开始上传"
            :auto-upload="false"
            @success="handleUploadSuccess"
            @error="handleUploadError"
            @progress="handleUploadProgress"
          />
        </view>
      </view>
    </view>

    <!-- 操作菜单弹窗 -->
    <view v-if="showActionsFlag" class="actions-overlay" @click="hideActions">
      <view class="actions-dialog" @click.stop>
        <view class="actions-header">
          <text class="actions-title">文档操作</text>
        </view>
        <view class="actions-list">
          <button class="action-item" @click="viewDocumentDetail">
            <text class="action-icon">👁️</text>
            <text>查看详情</text>
          </button>
          <button class="action-item" @click="reindexDocument">
            <text class="action-icon">🔄</text>
            <text>重新索引</text>
          </button>
          <button class="action-item delete-action" @click="deleteDocument">
            <text class="action-icon">🗑️</text>
            <text>删除文档</text>
          </button>
        </view>
        <button class="cancel-btn" @click="hideActions">取消</button>
      </view>
    </view>

    <!-- 文档详情弹窗 -->
    <view v-if="showDetail" class="detail-overlay" @click="hideDetail">
      <view class="detail-dialog" @click.stop>
        <view class="detail-header">
          <text class="detail-title">文档详情</text>
          <button class="close-btn" @click="hideDetail">✕</button>
        </view>
        <view class="detail-content">
          <view class="detail-item">
            <text class="detail-label">文件名：</text>
            <text class="detail-value">{{ currentDocument?.title }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">文件大小：</text>
            <text class="detail-value">{{
              formatFileSize(
                currentDocument?.content ? currentDocument.content.length : 0
              )
            }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">上传时间：</text>
            <text class="detail-value">{{
              formatDateTime(currentDocument?.createdAt)
            }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">状态：</text>
            <text class="detail-value">{{
              getStatusText(currentDocument?.errorMessage ? "error" : "success")
            }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">分块数：</text>
            <text class="detail-value">{{
              currentDocument?.chunksCount || 0
            }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { documentAPI } from "@/api/index";
import {
  getFileIcon,
  formatFileSize,
  getStatusText,
  getStatusClass,
  formatRelativeTime,
  formatDateTime,
  truncateText,
} from "@/utils/document.js";
import DocumentUploadSmart from "@/components/DocumentUploadSmart.vue";

// 响应式数据
const documents = ref([]);
const loading = ref(false);
const refreshing = ref(false);
const uploading = ref(false);
const showUpload = ref(false);
const showActionsFlag = ref(false);
const showDetail = ref(false);
const selectedFile = ref(null);
const currentDocument = ref(null);
const searchKeyword = ref("");
const uploadProgress = ref(0);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 计算属性
const noMore = computed(
  () => documents.value.length >= total.value && total.value > 0
);

// 生命周期
onMounted(() => {
  loadDocuments();
});

// 加载文档列表
const loadDocuments = async (refresh = false) => {
  if (refresh) {
    page.value = 1;
    documents.value = [];
  }

  if (loading.value) return;

  try {
    loading.value = true;
    const response = await documentAPI.getList(
      page.value,
      pageSize.value,
      searchKeyword.value
    );

    // 后端直接返回PagedResultDto，没有success字段包装
    const items = response.items || response.Items || [];
    const totalCount = response.totalCount || response.TotalCount || 0;

    // 处理文档数据，确保字段映射正确
    const processedItems = items
      .map((doc) => {
        // 检查文档是否有有效的ID
        if (!doc.id) {
          console.error("文档缺少ID:", doc);
          return null;
        }

        // 如果Title为空，使用Source作为文档名称
        const documentTitle =
          doc.title || doc.source || doc.fileName || "未知文档";

        return {
          ...doc,
          // 确保文档名称字段存在
          title: documentTitle,
          // 确保状态字段存在 - 根据ErrorMessage判断状态
          status: doc.errorMessage ? 3 : 2, // 3=失败, 2=已完成
          // 确保创建时间字段存在
          createdAt: doc.createdAt || doc.uploadedAt || doc.createdTime,
        };
      })
      .filter((doc) => doc !== null); // 过滤掉无效的文档

    if (refresh) {
      documents.value = processedItems;
    } else {
      documents.value.push(...processedItems);
    }
    total.value = totalCount;
  } catch (error) {
    console.error("加载文档失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  loadDocuments(true);
};

const clearSearch = () => {
  searchKeyword.value = "";
  loadDocuments(true);
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  loadDocuments(true);
};

// 加载更多
const loadMore = () => {
  if (!noMore.value && !loading.value) {
    page.value++;
    loadDocuments();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 上传相关
const showUploadDialog = () => {
  showUpload.value = true;
  selectedFile.value = null;
};

const hideUploadDialog = () => {
  showUpload.value = false;
  selectedFile.value = null;
  uploadProgress.value = 0;
};

const handleUploadSuccess = (file) => {
  console.log("上传成功:", file);
  uni.showToast({
    title: "上传成功",
    icon: "success",
  });
  hideUploadDialog();
  loadDocuments(true);
};

const handleUploadError = (error) => {
  console.error("上传失败:", error);
  uni.showToast({
    title: `上传失败: ${error.message}`,
    icon: "none",
  });
};

const handleUploadProgress = (progress) => {
  uploadProgress.value = progress;
};

// 文档操作
const showActions = (doc) => {
  console.log("showActions 被调用，文档对象:", doc);

  if (!doc || !doc.id) {
    console.error("传入的文档对象无效:", doc);
    uni.showToast({
      title: "文档信息错误",
      icon: "none",
      duration: 3000,
    });
    return;
  }

  console.log("设置当前文档:", doc);
  currentDocument.value = doc;
  showActionsFlag.value = true;
};

const hideActions = () => {
  showActionsFlag.value = false;
  currentDocument.value = null;
};

const viewDocument = (doc) => {
  uni.navigateTo({
    url: `/pages/documents/detail?id=${doc.id}`,
  });
};

const viewDocumentDetail = () => {
  if (!currentDocument.value || !currentDocument.value.id) {
    console.error("当前文档对象为空或缺少ID");
    uni.showToast({
      title: "文档信息错误，请重试",
      icon: "none",
      duration: 3000,
    });
    return;
  }
  hideActions();
  viewDocument(currentDocument.value);
};

const hideDetail = () => {
  showDetail.value = false;
  currentDocument.value = null;
};

const reindexDocument = async () => {
  if (!currentDocument.value || !currentDocument.value.id) {
    console.error("当前文档对象为空或缺少ID");
    uni.showToast({
      title: "文档信息错误，请重试",
      icon: "none",
      duration: 3000,
    });
    return;
  }

  const documentId = currentDocument.value.id;

  try {
    uni.showLoading({ title: "重新索引中..." });
    await documentAPI.reindex(documentId);

    uni.showToast({
      title: "重新索引成功",
      icon: "success",
    });

    hideActions();
    loadDocuments(true);
  } catch (error) {
    console.error("重新索引失败:", error);
    uni.showToast({
      title: "重新索引失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

const deleteDocument = async () => {
  console.log("deleteDocument 被调用，currentDocument:", currentDocument.value);

  if (!currentDocument.value || !currentDocument.value.id) {
    console.error("当前文档对象为空或缺少ID");
    uni.showToast({
      title: "文档信息错误，请重试",
      icon: "none",
      duration: 3000,
    });
    return;
  }

  const documentId = currentDocument.value.id;
  const documentTitle = currentDocument.value.title || "未知文档";

  uni.showModal({
    title: "确认删除",
    content: `确定要删除文档 "${documentTitle}" 吗？此操作不可恢复。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: "删除中..." });
          console.log("开始删除文档:", documentId);

          const result = await documentAPI.delete(documentId);
          console.log("删除结果:", result);

          uni.showToast({
            title: "删除成功",
            icon: "success",
          });

          hideActions();
          loadDocuments(true);
        } catch (error) {
          console.error("删除失败:", error);
          uni.showToast({
            title: error.message || "删除失败，请重试",
            icon: "none",
            duration: 3000,
          });
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.documents-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  /* 微信小程序兼容性 */
  box-sizing: border-box;
  overflow-x: hidden;
}

.header {
  padding: 40rpx 20rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20rpx);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.back-icon {
  font-size: 40rpx;
  color: white;
}

.header-title {
  font-size: 40rpx;
  font-weight: bold;
  color: white;
}

.upload-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  color: white;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.upload-icon {
  font-size: 32rpx;
}

.search-section {
  padding: 20rpx 20rpx;
}

.search-bar {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.search-icon {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.7);
}

.search-input {
  flex: 1;
  background: none;
  border: none;
  color: white;
  font-size: 28rpx;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.clear-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  font-size: 28rpx;
}

.documents-list {
  flex: 1;
  padding: 0 20rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  gap: 20rpx;
}

.empty-icon {
  font-size: 80rpx;
  color: rgba(255, 255, 255, 0.5);
}

.empty-text {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.7);
}

.empty-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 40rpx;
  color: white;
  font-size: 28rpx;
}

.documents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280rpx, 1fr));
  gap: 20rpx;
  padding: 20rpx 100rpx 40rpx 100rpx;
}

.document-card {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  padding: 20rpx;
  position: relative;
  backdrop-filter: blur(10rpx);
  transition: all 0.3s ease;
}

.document-card:active {
  transform: scale(0.98);
}

.document-icon {
  text-align: center;
  margin-bottom: 20rpx;
}

.icon-text {
  font-size: 60rpx;
}

.document-info {
  text-align: center;
}

.document-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: white;
  margin-bottom: 10rpx;
  word-break: break-all;
  line-height: 1.3;
  max-height: 2.6em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.document-size,
.document-date {
  display: block;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 5rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.document-actions {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
}

.action-btn {
  background: rgba(0, 0, 0, 0.1);
  border: none;
  border-radius: 50%;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-icon {
  font-size: 32rpx;
  color: white;
}

.document-status {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
}

.status-pending {
  background: rgba(255, 193, 7, 0.3);
  color: #ffc107;
}

.status-processing {
  background: rgba(0, 123, 255, 0.3);
  color: #007bff;
}

.status-completed {
  background: rgba(40, 167, 69, 0.3);
  color: #28a745;
}

.status-failed {
  background: rgba(220, 53, 69, 0.3);
  color: #dc3545;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 40rpx;
}

.loading-text,
.no-more-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 28rpx;
}

/* 弹窗样式 */
.upload-overlay,
.actions-overlay,
.detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.upload-dialog,
.actions-dialog,
.detail-dialog {
  background: white;
  border-radius: 20rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.upload-header,
.actions-header,
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.upload-title,
.actions-title,
.detail-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
}

.upload-content,
.actions-list,
.detail-content {
  padding: 40rpx;
}

.file-select-btn,
.upload-submit-btn {
  width: 100%;
  padding: 30rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  margin-bottom: 20rpx;
}

.file-select-btn {
  background: #f0f0f0;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.upload-submit-btn {
  background: #667eea;
  color: white;
}

.upload-submit-btn:disabled {
  background: #ccc;
}

.selected-file {
  display: block;
  text-align: center;
  color: #666;
  margin: 20rpx 0;
}

.action-item {
  width: 100%;
  padding: 30rpx;
  border: none;
  border-bottom: 1rpx solid #eee;
  background: none;
  display: flex;
  align-items: center;
  gap: 20rpx;
  font-size: 32rpx;
  color: #333;
}

.action-item:last-child {
  border-bottom: none;
}

.delete-action {
  color: #dc3545;
}

.cancel-btn {
  width: 100%;
  padding: 30rpx;
  border: none;
  border-top: 1rpx solid #eee;
  background: none;
  font-size: 32rpx;
  color: #666;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
}

.detail-label {
  font-weight: bold;
  color: #333;
  min-width: 120rpx;
}

.detail-value {
  color: #666;
  flex: 1;
}

/* 微信小程序特定优化 */
@media screen and (max-width: 750rpx) {
  .documents-grid {
    grid-template-columns: repeat(auto-fill, minmax(240rpx, 1fr));
    gap: 15rpx;
  }

  .document-card {
    padding: 15rpx;
  }

  .header {
    padding: 30rpx 15rpx 15rpx;
  }

  .search-section {
    padding: 15rpx 15rpx;
  }

  .documents-list {
    padding: 0 15rpx;
  }

  .document-name {
    font-size: 26rpx;
    max-height: 2.4em;
  }
}

/* 超小屏幕优化 */
@media screen and (max-width: 600rpx) {
  .documents-grid {
    grid-template-columns: repeat(auto-fill, minmax(200rpx, 1fr));
    gap: 10rpx;
  }

  .document-card {
    padding: 12rpx;
  }

  .document-name {
    font-size: 26rpx;
  }

  .document-size,
  .document-date {
    font-size: 22rpx;
  }
}

/* 微信小程序特定样式 */
.upload-dialog,
.actions-dialog,
.detail-dialog {
  /* 确保在微信小程序中正确显示 */
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

/* 防止微信小程序中的滚动问题 */
.documents-list {
  -webkit-overflow-scrolling: touch;
}

/* 优化微信小程序中的按钮点击效果 */
.upload-btn,
.action-btn,
.close-btn {
  -webkit-tap-highlight-color: transparent;
}
</style>
